package com.jml.AOP004.责任链通知005.invocation.impl;

import com.jml.AOP004.责任链通知005.interceptor.MethodInterceptor;
import com.jml.AOP004.责任链通知005.invocation.MethodInvocation;
import java.lang.reflect.Method;
import java.util.List;


public class DefaultMethodInvacation implements MethodInvocation {
    
    /**
     * 存放所有的通知
     */
    private List<MethodInterceptor> listMethodInterceptor;
    private Object target;// 目标对象
    private Method method;// 目标方法
    private Object args[];// 目标参数
    // 最终使用反射机制执行目标方法
    private int index;// 记录当前链调用的位置

    public DefaultMethodInvacation(List<MethodInterceptor> listMethodInterceptor, Object target, Method method, Object[] args) {
        this.listMethodInterceptor = listMethodInterceptor;
        this.target = target;
        this.method = method;
        this.args = args;
    }

    public DefaultMethodInvacation(List<MethodInterceptor> listMethodInterceptor) {
        this.listMethodInterceptor = listMethodInterceptor;
    }

    /**
     * 调用链形成
     *
     * @return
     */
    @Override
    public void process() throws Exception {
        if (index == listMethodInterceptor.size()) {
            method.invoke(target, args); //  执行目标
            return;
        }
        MethodInterceptor methodInterceptor = listMethodInterceptor.get(index);
        index++;
        methodInterceptor.invoke(this);
    }
}
